#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys, shlex, numpy

##Read a Paramater
##@param filename The input filename
##@param label The name of the parameter
##@return a dictionary with the data
def leGAMSParameter(filename, label):
    ret = {}
    f = open(filename)
    line = f.readline()
    while not("PARAMETERS" in line.upper()):
        line = f.readline()
        #cursor posicionado na linha apos "Parameters"
    while line:
        sair = 0
        colunas = shlex.split(line)
        if label in colunas:
            #cursor posicionado na linha do label
            while not("/" in line):
                line = f.readline()
            linhaLimpa = shlex.split(line.replace("/", ""))
            if (len(linhaLimpa) > 0 and (shlex.split(line)[-1] != "/")):
                index = "0"
                if (len(linhaLimpa) >= 2 and linhaLimpa[-2] != label):
                    index = linhaLimpa[-2]
                ret[index] = linhaLimpa[-1]
                if (line.count("/") != 2):
                    line = f.readline()
                    linhaLimpa = shlex.split(line.replace("/", ""))
                    if (len(linhaLimpa) > 0):
                        index = "0"
                        if (len(linhaLimpa) >= 2):
                            index = linhaLimpa[-2]
                        ret[index] = linhaLimpa[-1]
            else:
                line = f.readline()
                linhaLimpa = shlex.split(line.replace("/", ""))
                if (len(linhaLimpa) > 0):
                    index = "0"
                    if (len(linhaLimpa) >= 2):
                        index = linhaLimpa[-2]
                    ret[index] = linhaLimpa[-1]
                            
            while not("/" in line):
                line = f.readline()
                linhaLimpa = shlex.split(line.replace("/", "").replace(";", ""))
                if (len(linhaLimpa) > 0):
                    index = "0"
                    if (len(linhaLimpa) >= 2):
                        index = linhaLimpa[-2]
                    ret[index] = linhaLimpa[-1]
            
            return(ret)
            if sair == 1:
                break;
        line = f.readline()
    f.close()
    return(1)

##Read a Table
##@param filename The input filename
##@param label The name of the parameter
##@return a dictionary with the data
def leGAMSTable(filename, label):
    ret = {}
    f = open(filename)
    line = f.readline()
    while not("TABLE" in line.upper() and label.upper() in line.upper()):
        line = f.readline()
    line = f.readline()
    #cursor posicionado na linha apos a linha que define a tabela
    colLabels = shlex.split(line)   #todos os labels das colunas
    line = f.readline()
    contents = []
    contents.append(shlex.split(line.replace(";", "")))
    while not (";" in line):
        line = f.readline()
        if (len(line.replace(";", "").strip()) > 0):
            contents.append(shlex.split(line.replace(";", "")))

    linhaAtual, colunaAtual = 0, 1
    while (linhaAtual < len(contents)):
        #print (linhaAtual)
        tmp_line = {}
        while (colunaAtual <= len(colLabels)):            
            #print (">>" + str(colunaAtual) + "<" + str(len(colLabels)) + " " + str(linhaAtual) + "<" + str(len(contents)))
            a = contents[linhaAtual][colunaAtual]
            #ret[linhaAtual][colunaAtual] = float(a)
            if len(a) == 0:
                tmp_line[colLabels[colunaAtual-1]] = "0"
            else:
                tmp_line[colLabels[colunaAtual-1]] = a
            colunaAtual = colunaAtual + 1
        ret[contents[linhaAtual][0]] = tmp_line  #isso ta errado
        
        colunaAtual = 0
        linhaAtual = linhaAtual + 1
    #print(ret)
    #print (colLabels)
##    for i in ret:
##        print i,
##        for j in ret[i]:
##            print "\t"+str(j),
##        print ""
##    exit()
    f.close()
    return(ret)

##This function format a value into a GAMS style. Used by the formatGAMSTable
##@param value the value to be formatted
##@param size the lenght of the returning string
def formatGAMSCol(value, size=9):
    sp = " "*size
    sptrim = sp[len(str(value)):]
    return (str(value)+sptrim)

##This function format a vector given in "data" to a GAMS-formatted 
##parameter named as defined in "label"
def formatGAMSParameter(data, label):
    ret = label + """
/
"""
    for k,v in data.iteritems():
        ret = ret + str(k) + "\t" + str(v) +"""
"""
    ret = ret + "/"
    return(ret)

##This function format a dictionary given in "data" to a GAMS-formatted 
##table named as defined in "label"
def formatGAMS2DTable(data, label, fstRow, fstCol):
    ret = label + """
""" + formatGAMSCol("")
    for a in fstCol:
        ret = ret + formatGAMSCol(a)
            
    ret = ret + "\n"
    currLine = 0
    while currLine < len(fstRow):
        ret = ret + formatGAMSCol(fstRow[currLine]) 
        currCol = 0
        while currCol < len(fstCol):
            lblLine = str(fstRow[currLine])
            lblCol = str(fstCol[currCol])
            #print lblLine, lblCol
      #      print "\t",data[lblLine]
            ret = ret + formatGAMSCol(data[lblLine][lblCol]) 
            currCol = currCol + 1
        ret = ret + "\n"
        currLine = currLine + 1
    return ret
